import { defineStore } from 'pinia'

export const useBlog = defineStore('blog', {
  state: () => ({
    blogs: [],
    page: {
      start: 0,
      page: 20
    },
  }),
  actions: {
    init() {
      this.blogs = []
      this.page.start = 0
      return this
    },

    // /* 下面是Blog-------------------------------- */
    addPageBlogs(fun) {
      let start = this.page.start, page = this.page.page
      myPost("/blogs", { start, page }, pageBlogs => {
        this.blogs.push(...pageBlogs)
        // 数据获取完毕,要通过回调告知组件，isNoMore
        if (pageBlogs.length < page) fun(true, pageBlogs) // true没有数据
        else fun(false, pageBlogs)
      })
      this.page.start = start + page
    },



    // 静态方法============================================

    // 传入一个blogId
    getBlogsbyId(id, fun) {
      myPost("/blog", { id }, data => {
        data.blogData = JSON.parse(data.blogData || '[]')
        data.blogInfo = JSON.parse(data.blogInfo || '{}')
        fun(data)
      });
    },
    // 参数二要传入一个数组，依次是 username,func
    getBlogsbyUsername(username, start, page, func) {
      myPost("/blogs_by_username", { username, start, page },
        data => {
          // 如果没有数据要通过回调告知组件，noMore
          if (data.length < 1) func(data, false)
          else func(data, true)
        }
      )
    },
    // 发布博客
    releaseBlog(blog, fun) {
      console.log(blog);
      myPost('/release', { userToken: User.token, "blogJson": JSON.stringify(blog) }, data => {
        fun && fun(data)
      })
    },


  },
})